# React

In this document, you will learn how to build a React application using Rsbuild.

## Create React Project

You can use `create-rsbuild` to create a project with Rsbuild + React. Just execute the following command:

import { PackageManagerTabs } from '@theme';

<PackageManagerTabs
  command={{
    npm: 'npm create rsbuild@latest',
    yarn: 'yarn create rsbuild',
    pnpm: 'pnpm create rsbuild@latest',
    bun: 'bun create rsbuild@latest',
  }}
/>

Then select `React` when prompted to "Select framework".

## Use React in an existing project

To compile React, you need to register the Rsbuild [React Plugin](/plugins/list/plugin-react). The plugin will automatically add the necessary configuration for React builds.

For example, register in `rsbuild.config.ts`:

```ts title="rsbuild.config.ts"
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';

export default defineConfig({
  plugins: [pluginReact()],
});
```

:::tip
For projects using Create React App, you can refer to the [CRA Migration Guide](/guide/migration/cra).
:::

## Use SVGR

Rsbuild supports convert SVG to React components via [SVGR](https://react-svgr.com/).

If you need to use svgr, you also need to register the [SVGR plugin](/plugins/list/plugin-svgr).

## React Fast Refresh

Rsbuild uses React's official [Fast Refresh](https://www.npmjs.com/package/react-refresh) capability to perform component hot updates.

Note that React Refresh requires components to be written according to the standards. Otherwise HMR may not work. You can use [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) for validation.

For example, if the hot update of the React component cannot take effect, or the state of the React component is lost after the hot update, it is usually because your React component uses an anonymous function. In the official practice of React Fast Refresh, it is required that the component cannot be an anonymous function, otherwise the state of the React component cannot be preserved after hot update.

Here are some examples of wrong usage:

```tsx
// bad
export default function () {
  return <div>Hello World</div>;
}

// bad
export default () => <div>Hello World</div>;
```

The correct usage is to declare a name for each component function:

```tsx
// good
export default function MyComponent() {
  return <div>Hello World</div>;
}

// good
const MyComponent = () => <div>Hello World</div>;

export default MyComponent;
```

## React Compiler

React Compiler is an experimental compiler introduced in React 19 that can automatically optimize your React code.

Before you start using React Compiler, it's recommended to read the [React Compiler documentation](https://react.dev/learn/react-compiler) to understand the functionality, current state, and usage of the React Compiler.

### How to use

The steps to use React Compiler in Rsbuild:

1. Upgrade versions of `react` and `react-dom` to 19. If you are unable to upgrade, you can install the extra [react-compiler-runtime](https://www.npmjs.com/package/react-compiler-runtime) package which will allow the compiled code to run on versions prior to 19.
2. React Compiler currently only provides a Babel plugin, you need to install [@rsbuild/plugin-babel](/plugins/list/plugin-babel) and [babel-plugin-react-compiler](https://www.npmjs.com/package/babel-plugin-react-compiler).
3. Register the Babel plugin in your Rsbuild config file:

```ts title="rsbuild.config.ts"
import { defineConfig } from '@rsbuild/core';
import { pluginBabel } from '@rsbuild/plugin-babel';
import { pluginReact } from '@rsbuild/plugin-react';

export default defineConfig({
  plugins: [
    pluginReact(),
    pluginBabel({
      include: /\.(?:jsx|tsx)$/,
      babelLoaderOptions(opts) {
        opts.plugins?.unshift('babel-plugin-react-compiler');
      },
    }),
  ],
});
```

> You can also refer to the [example project](https://github.com/rspack-contrib/rspack-examples/tree/main/rsbuild/react-compiler-babel).

### Configuration

Set the config for React Compiler as follows:

```ts title="rsbuild.config.ts"
import { defineConfig } from '@rsbuild/core';
import { pluginBabel } from '@rsbuild/plugin-babel';
import { pluginReact } from '@rsbuild/plugin-react';

const ReactCompilerConfig = {
  /* ... */
};

export default defineConfig({
  plugins: [
    pluginReact(),
    pluginBabel({
      include: /\.(?:jsx|tsx)$/,
      babelLoaderOptions(opts) {
        opts.plugins?.unshift([
          'babel-plugin-react-compiler',
          ReactCompilerConfig,
        ]);
      },
    }),
  ],
});
```

For React 17 and 18 projects, you need to install [react-compiler-runtime](https://www.npmjs.com/package/react-compiler-runtime) and specify the `target`:

```ts title="rsbuild.config.ts"
const ReactCompilerConfig = {
  target: '18', // '17' | '18' | '19'
};
```

## Router

### TanStack Router

[TanStack Router](https://tanstack.com/router/) is a fully type-safe React router with built-in data fetching, stale-while revalidate caching and first-class search-param APIs.

TanStack Router provides `@tanstack/router-plugin` to integrate with Rsbuild, which provides support for file-based routing. See:

- [File-Based Routing documentation](https://tanstack.com/router/latest/docs/framework/react/guide/file-based-routing)
- [TanStack Router + Rsbuild Example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-rspack-file-based)

## CSS-in-JS

### Use styled-components

Rsbuild supports compiling [styled-components](https://github.com/styled-components/styled-components), improve the debugging experience and add server-side rendering support to styled-components.

If you need to use styled-components, We recommend using the [@rsbuild/plugin-styled-components](https://github.com/rsbuild-contrib/rsbuild-plugin-styled-components).

> You can refer to this example: [styled-components](https://github.com/rspack-contrib/rspack-examples/tree/main/rsbuild/styled-components).

### Using Emotion

Rsbuild supports compiling [Emotion](https://github.com/emotion-js/emotion), you can add the following configuration to use:

- [swcReactOptions.importSource](/plugins/list/plugin-react#swcreactoptions)
- [@swc/plugin-emotion](https://www.npmjs.com/package/@swc/plugin-emotion)

```ts title="rsbuild.config.ts"
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';

export default defineConfig({
  plugins: [
    pluginReact({
      swcReactOptions: {
        importSource: '@emotion/react',
      },
    }),
  ],
  tools: {
    swc: {
      jsc: {
        experimental: {
          plugins: [['@swc/plugin-emotion', {}]],
        },
      },
    },
  },
});
```

> You can refer to this example: [emotion](https://github.com/rspack-contrib/rspack-examples/tree/main/rsbuild/emotion).

### Use styled-jsx

You can use [styled-jsx](https://github.com/vercel/styled-jsx) through [@swc/plugin-styled-jsx](https://www.npmjs.com/package/@swc/plugin-styled-jsx):

```ts title="rsbuild.config.ts"
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';

export default defineConfig({
  plugins: [pluginReact()],
  tools: {
    swc: {
      jsc: {
        experimental: {
          plugins: [['@swc/plugin-styled-jsx', {}]],
        },
      },
    },
  },
});
```

Please note, you must select the SWC plugin that matches the current version of `@swc/core` for SWC to work, see [tools.swc](/config/tools/swc).

> You can refer to this example: [styled-jsx](https://github.com/rspack-contrib/rspack-examples/tree/main/rsbuild/styled-jsx).

### Use vanilla-extract

Rsbuild supports [@vanilla-extract/webpack-plugin](https://www.npmjs.com/package/@vanilla-extract/webpack-plugin). You can add the following config to use [vanilla-extract](https://github.com/vanilla-extract-css/vanilla-extract):

```ts title="rsbuild.config.ts"
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';
import { VanillaExtractPlugin } from '@vanilla-extract/webpack-plugin';

export default defineConfig({
  plugins: [
    pluginReact({
      reactRefreshOptions: {
        exclude: [/\.css\.ts$/],
      },
    }),
  ],
  tools: {
    rspack: {
      plugins: [new VanillaExtractPlugin()],
    },
  },
});
```

> You can refer to this example: [vanilla-extract](https://github.com/rspack-contrib/rspack-examples/tree/main/rsbuild/vanilla-extract).

### Use StyleX

You can use [StyleX](https://github.com/facebook/stylex) via [unplugin-stylex](https://github.com/eryue0220/unplugin-stylex):

```ts title="rsbuild.config.ts"
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';
import stylexPlugin from 'unplugin-stylex/rspack';

export default defineConfig({
  plugins: [pluginReact()],
  tools: {
    rspack: {
      plugins: [stylexPlugin()],
    },
  },
});
```

> You can refer to this example: [stylex](https://github.com/rspack-contrib/rspack-examples/tree/main/rsbuild/stylex).
